package adminService

import (
	"fmt"
	"gin/chibuda/app/utils"
	"github.com/gohouse/gorose/v2"
	"strings"
	//"sync"
)

func AdminUserList(data map[string]string) utils.Service{
	if data["page"] == "" {
		data["page"] = "1"
	}
	if data["pageCount"] == "" {
		data["pageCount"] = "10"
	}
	query := Db().Table("admin_user a").
		LeftJoin("admin_role b","a.role_id","=","b.id").
		Fields("a.id,a.name,a.nick_name,a.last_login_time,a.status,a.role_id,b.name as role_name")
	if data["keyWord"] != ""{
		query.Where("a.nick_name","like","%"+data["keyWord"]+"%").OrWhere("a.name","like","%"+data["keyWord"]+"%")
	}
	list , _ :=query.
		Limit(utils.Int(data["pageCount"])).
		Paginate(utils.Int(data["page"]))
	return utils.Success(list)
}

func AdminUserEdit(data map[string]string) utils.Service{
	if data["password"] != "" {
		data["solt"] = utils.CreateRandomString(10)
		data["password"] = utils.Md5(data["password"] + data["solt"] )
	}else{
		delete(data, "password")
	}
	if data["id"] != "" {
		res,err := Db().Table("admin_user").
			Where("id",data["id"]).
			Data(data).
			Update()
		if err!=nil || res == 0 {
			return utils.Error(err)
		}
	}else{
		if data["role_id"] == "" || data["password"] == "" || data["name"] == ""  || data["nick_name"] == ""{
			return utils.Error("参数不能为空")
		}
		delete(data,"id")
		user,_:=Db().Table("admin_user").Where("name",data["name"]).First()
		if user != nil{
			return utils.Error( data["name"] + "账号已存在")
		}
		res,err := Db().Table("admin_user").
			Data(data).
			Insert()
		if err!=nil || res == 0 {
			return utils.Error("添加失败")
		}
	}
	return utils.Success()
}

//获取菜单
func GetMenu() utils.Service{
	list, _ :=Db().Table("admin_menu").Order("sort desc").Get()
	res := GetRouterChild(0 ,list)
	return utils.Success(res)
}

func GetRouterChild(pid int64 , list []gorose.Data) interface{}{
	var arr []gorose.Data
	for _,v :=range list  {
		if pid == v["pid"] {
			v["child"] = GetRouterChild(v["id"].(int64),list)
			arr = append(arr,v)
		}
	}
	return arr
}

func MenuEdit(data map[string]string) utils.Service{
	if data["id"] != "" {
		res,err := Db().Table("admin_menu").
			Where("id",data["id"]).
			Data(data).
			Update()
		if err!=nil || res == 0 {
			return utils.Error(err)
		}
	}else{
		delete(data,"id")
		res,err := Db().Table("admin_menu").
			Data(data).
			Insert()
		if err!=nil || res == 0 {
			return utils.Error("添加失败")
		}
	}
	return utils.Success()
}


func MenuDel (data map[string]string) utils.Service{
	res,err:=DB.Table("admin_menu").
		Where("id",data["id"]).
		OrWhere("pid",data["id"]).
		Delete()
	if err!=nil || res == 0 {
		return utils.Error("删除失败")
	}
	return utils.Success()
}

//获取所有路由
func AdminUserGetRole() utils.Service{
	roleList , _:=Db().Table("admin_role").Get()
	return utils.Success(roleList)
}

func AdminUserDel(id interface{}) utils.Service{
	res,err :=Db().Table("admin_user").
		Where("id",id).
		Delete()
	if err!=nil || res == 0 {
		return utils.Error("删除失败")
	}
	return utils.Success()
}

func RoleList(data map[string]string) utils.Service{
	if data["page"] == "" {
		data["page"] = "1"
	}
	if data["pageCount"] == "" {
		data["pageCount"] = "10"
	}
	query := Db().Table("admin_role")
	if data["keyWord"] != ""{
		query.Where("name","like","%"+data["keyWord"]+"%")
	}
	list , _ :=query.
		Limit(utils.Int(data["pageCount"])).
		Paginate(utils.Int(data["page"]))
	return utils.Success(list)
}

func RoleEdit(data map[string]string) utils.Service{
	if data["id"] != "" {
		res,err := Db().Table("admin_role").
			Where("id",data["id"]).
			Data(data).
			Update()
		if err!=nil || res == 0 {
			return utils.Error(err)
		}
	}else{
		delete(data,"id")
		res,err := Db().Table("admin_role").
			Data(data).
			Insert()
		if err!=nil || res == 0 {
			return utils.Error("添加失败")
		}
	}
	return utils.Success()
}

func RoleDel(id interface{}) utils.Service{
	rs,_ :=Db().Table("admin_user").
		Where("role_id",id).
		First()
	if rs != nil{
		return utils.Error("请先解除管理员的该角色")
	}
	err := Db().Transaction(
		func(db gorose.IOrm) error {
			_,err := db.Table("admin_role").
						Where("id",id).
						Delete()
			if err!=nil {
				return err
			}
			return nil
		},
		func(db gorose.IOrm) error {
			_,err := db.Table("amdin_role_menu").Where("role_id",id).Delete()
			if err!=nil {
				return err
			}
			return nil
		},
	)
	if err!=nil {
		return utils.Error("删除失败")
	}
	return utils.Success()
}

func RoleMenu(id interface{}) utils.Service{
	res,_:=Db().Table("amdin_role_menu").Where("role_id",id).Where("is_mid",1).Get()
	return utils.Success(res)
}

func RoleMenuAuth(data map[string]string) utils.Service{
	idArr := strings.Split(data["idArr"], ",")
	idArrMid := strings.Split(data["idArrMid"], ",")
	if len(idArr) <= 0{
		return utils.Error("请为角色分配权限")
	}
	var insertData []map[string]interface{}
	for _,v:=range idArr {
		if v == "0"{
			continue
		}
		idata :=make( map[string]interface{} )
		idata["role_id"] = data["id"]
		idata["menu_id"] = v
		idata["is_mid"] = 1
		insertData = append(insertData,idata)
	}
	for _,v := range idArrMid {
		if v == "0"{
			continue
		}
		idMid :=make( map[string]interface{} )
		idMid["role_id"] = data["id"]
		idMid["menu_id"] = v
		idMid["is_mid"] = 2
		insertData = append(insertData,idMid)
	}
	fmt.Println(insertData)
	err := Db().Transaction(
		func(db gorose.IOrm) error {
			_,err := db.Table("amdin_role_menu").Where("role_id",data["id"]).Delete()
			if err!=nil {
				return err
			}
			return nil
		},
		func(db gorose.IOrm) error {
			_,err := db.Table("amdin_role_menu").Data(insertData).Insert()
			if err!=nil {
				return err
			}
			return nil
		},
	)
	if err!=nil {
		return utils.Error("删除失败")
	}
	return utils.Success()
}
